package com.dpj.seckill.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dpj.seckill.exception.GlobalException;
import com.dpj.seckill.mapper.TUserMapper;
import com.dpj.seckill.pojo.TUser;
import com.dpj.seckill.service.TUserService;
import com.dpj.seckill.utils.CookieUtil;
import com.dpj.seckill.utils.MD5Util;
import com.dpj.seckill.utils.UUIDUtil;
import com.dpj.seckill.utils.ValidatorUtil;
import com.dpj.seckill.vo.LoginVo;

import com.dpj.seckill.vo.RespBean;
import com.dpj.seckill.vo.RespBeanEnum;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-07-03
 */
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements TUserService {

    @Autowired
    private TUserMapper tUserMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public RespBean doLogin(LoginVo loginVo,HttpServletRequest request, HttpServletResponse response) {
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();

//        if(StringUtils.isEmpty(mobile)||StringUtils.isEmpty(password)){
//            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
//        }
//        if(!ValidatorUtil.isMobile(mobile)){
//            return RespBean.error(RespBeanEnum.MOBILE_ERROR);
//        }
        TUser user=tUserMapper.selectById(mobile);
        if(null==user){
          //  return RespBean.error(RespBeanEnum.LOGIN_ERROR);
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }

        //校验密码

        //生成cookie
        if(!MD5Util.formPassToDBPass(password,user.getSalt()).equals(user.getPassword())){
            //return RespBean.error((RespBeanEnum.LOGIN_ERROR));
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }
        String ticket = UUIDUtil.uuid();
       // request.getSession().setAttribute(ticket,user);
        redisTemplate.opsForValue().set("user"+ticket,user);
        CookieUtil.setCookie(request,response,"userTicket",ticket);

        return RespBean.success(ticket);
    }

    @Override
    public TUser getUserByCookie(String ticket,HttpServletRequest request,HttpServletResponse response) {


        if(StringUtils.isEmpty(ticket)){
            return null;
        }
       TUser user= (TUser) redisTemplate.opsForValue().get("user" + ticket);
        if(user!=null){
            CookieUtil.setCookie(request,response,"userTicket",ticket);
        }
        return user;
    }


}
